
package com.dps.omc.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dps.omc.model.Job;
import com.dps.omc.model.Task;
import com.dps.omc.model.User;
import com.dps.omc.publish.TaskManager;
import com.dps.omc.service.IJobService;
import com.dps.omc.service.ITaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dps.common.domain.view.BizData4Page;
import com.dps.common.utils.IdGenerator;
import com.dps.common.utils.JsonResult;
import com.dps.common.utils.PageParam;
import com.dps.common.utils.Constants;

@Controller
public class TaskAction extends AbstractAdminController<ITaskService>{

    @Autowired
    private ITaskService taskService;
    @Autowired
    private IJobService jobService;
    @Autowired
    private TaskManager taskManager;
    @RequestMapping(value="/task/list")
    public String list(Task task, ModelMap model, PageParam pageParam, HttpServletRequest request, HttpServletResponse response){

        //获取参数
    	Map<String, Object> conditions = getQueryMap(task); 	
    	BizData4Page<Task> pageCtx = doPage(model, conditions, pageParam);
    	model.addAttribute("task", task);
    	return "/module/task/list";
    }

    @RequestMapping(value="/task/listbyjob")
    public String list(String jobId,ModelMap model,HttpServletRequest request,HttpServletResponse response){

        List<Task> tasks = taskService.findListByJobId(jobId);

        Job job = jobService.fetch(jobId);
        model.addAttribute("array", tasks);
        model.addAttribute("jobId", jobId);
        model.addAttribute("job", job);
        return "/module/task/listbyjob";
    }

    @RequestMapping(value="/task/add")
    public String add(ModelMap model,HttpServletRequest request,HttpServletResponse response){

    	model.addAttribute("task", new Task());
        return "module/task/edit";
    }    
    
    @RequestMapping(value="/task/edit")
    public String edit(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response){
    	
    	Task task = taskService.fetch(id);
    	model.addAttribute("task", task);
        return "module/task/edit";
    }    
    
    @RequestMapping(value="/task/save")
    @ResponseBody
    public String save(HttpServletRequest request,Task task){
		boolean isAddNew = StringUtils.isBlank(task.getId())?true:false;
        User user=getCurrentUser();
		if(isAddNew)
		{
			task.setId(IdGenerator.createNewId());
            task.setCreaterId(user.getId());
            task.setCreaterName(user.getRealName());
			taskService.add(task);
		}
		else
		{
			taskService.update(task);
		}
        return JsonResult.saveSuccessClose(Constants.MAIN_TAB).toString();
    }    
    
    @RequestMapping(value="/task/delete")
    @ResponseBody
    public String delete(String ids,HttpServletRequest request){
    	
    	taskService.deleteByIds(ids);
    	return JsonResult.DELETE_SUCCESS.toString();
    }

//    @RequestMapping(value="/task/preview")
//    @ResponseBody
//    public String preview(String id,HttpServletRequest request) throws Exception {
//
//        Task task = taskService.fetch(id);
//        Job job = jobService.fetch(task.getJobId());
//        String cmd = taskManager.generateCmd(job,task);
//        return cmd;
//    }

    @RequestMapping(value="/task/preview")
    public String preview(String id,ModelMap model,HttpServletRequest request,HttpServletResponse response) throws Exception {

        Task task = taskService.fetch(id);
        Job job = jobService.fetch(task.getJobId());
        String cmd = taskManager.generateCmd(job,task);
        if(StringUtils.isNotBlank(cmd))
        {
            cmd = cmd.replaceAll("<","&lt;");
            cmd = cmd.replaceAll(">","&gt;");
            cmd = cmd.replaceAll("\n","<br/>");//日志换行
        }
        model.addAttribute("cmd",cmd);
        return "module/task/preview";
    }



//    @RequestMapping(value="/task/log")
//    @ResponseBody
//    public String log(String id,HttpServletRequest request) throws Exception {
//
//        Task task = taskService.fetch(id);
//        String msg = task.getReturnMsg();
//        return msg;
//    }

    @RequestMapping(value="/task/log")
    public String log(String id,HttpServletRequest request,ModelMap model) throws Exception {

        Task task = taskService.fetch(id);
        String msg = task.getReturnMsg();
        if(StringUtils.isNotBlank(msg))
        {
            msg = msg.replaceAll("\n","<br/>");//日志换行
        }
        model.addAttribute("task",task);
        model.addAttribute("msg",msg);
        return "module/task/log";
    }


    @RequestMapping(value="/task/run")
    @ResponseBody
    public String run(String id,HttpServletRequest request) throws Exception {

        User user = getCurrentUser();
        Task task = taskService.fetch(id);
        Job job = jobService.fetch(task.getJobId());
        taskManager.run(job,task,user);
        return JsonResult.operateSuccess(Constants.MAIN_TAB).toString();
    }

    protected Map getQueryMap(Task task)
    {
        Map<String, Object> conditions = new HashMap();

        conditions.put("agentId", task.getAgentId());
        conditions.put("jobId", task.getJobId());
        conditions.put("templateId", task.getTemplateId());
        conditions.put("artifactId", task.getArtifactId());
        conditions.put("clientIp", task.getClientIp());
        conditions.put("returnMsg", task.getReturnMsg());
        conditions.put("planDate", task.getPlanDate());
        conditions.put("actualDate", task.getActualDate());
        conditions.put("isTimer", task.getIsTimer());
        conditions.put("note", task.getNote());
        conditions.put("status", task.getStatus());
        conditions.put("startDate", task.getStartDate());
        conditions.put("endDate", task.getEndDate());
        conditions.put("createDate", task.getCreateDate());
        conditions.put("createrId", task.getCreaterId());
        conditions.put("createrName", task.getCreaterName());
        conditions.put("lastModifiedTime",task.getLastModifiedTime());
        conditions.put("lastModifiedId",task.getLastModifiedId());
        conditions.put("lastModifiedName",task.getLastModifiedName());
        return conditions;
    }

    @Override
    protected ITaskService getMainService() {
        return taskService;
    }

    @Override
    protected String getMainObjName() {
        return "task";
    }

    @Override
    protected String getViewTitle() {
        return "task";
    }
}
